<?php
/**
 * Created by JetBrains PhpStorm.
 * User: Victor
 * Date: 03.12.11
 * Time: 16:07
 * To change this template use File | Settings | File Templates.
 */

class Auth_Auth2 extends Core_BaseModel
{

    public function isAuth()
    {
        $isAuth = false;
        $isAuthorized = $this->isAuthorizedUserVer2();
        if ($isAuthorized != -1) $isAuth = true;

        return $isAuth;
    }

    public function getUserIdByLogin($login)
    {
        //echo "getUserIdByLogin($login)<br/>";
        //$login = $login['name'];
        $pdo = $this->dataModule->getConnection();
        $sql = "SELECT idaccount from `dzundza_account` where login = :login";
        $stn = $pdo->prepare($sql);
        $stn->bindParam(':login', $login, PDO::PARAM_STR);
        $stn->execute();
        $result = $stn->fetch(PDO::FETCH_ASSOC);
        return $result['idaccount'];


    }

    public function authorizeUser($login, $hash)
    {
        $id = $this->getUserIdByLogin($login);
        $pdo = $this->dataModule->getConnection();
        $sql = "UPDATE `dzundza_account` SET `hash`=:hash  WHERE `idaccount`=:id";
        $stn = $pdo->prepare($sql);
        $stn->bindParam(':hash', $hash, PDO::PARAM_STR);
        $stn->bindParam(':id', $idUser, PDO::PARAM_INT);
        $result = $stn->execute();
        // if (!$result) var_dump($stn->errorInfo());


    }

    public function insertHashToDB($idUser, $hash)
    {
        $pdo = $this->dataModule->getConnection();
        $sql = "UPDATE `dzundza_account` SET `hash`=:hash  WHERE `idaccount`=:id";
        $stn = $pdo->prepare($sql);
        $stn->bindParam(':hash', $hash, PDO::PARAM_STR);
        $stn->bindParam(':id', $idUser, PDO::PARAM_INT);
        $result = $stn->execute();
       // if (!$result) var_dump($stn->errorInfo());

    }


    public function isAuthorizedUser($login, $sessid, $cookieid)
    {
        $hashFromDB = $this->getHash($this->getUserIdByLogin($login));
        if ($hashFromDB == $sessid && $hashFromDB == $cookieid) {
            return 1;
        }
        else return 0;

    }

    public function  getHash($id)
    {
        //echo "getHash($id)<br/>";
        $pdo = $this->dataModule->getConnection();
        $sql = "SELECT `hash` from `dzundza_account` where `idaccount` = :id";
        $stn = $pdo->prepare($sql);
        $stn->bindParam(':id', $id, PDO::PARAM_STR);
        $stn->execute();
        $result = $stn->fetch(PDO::FETCH_ASSOC);
        //echo "return" . $result['hash'] . "<br/>";
        return $result['hash'];

    }

    public function checkUser($login, $password)
    {
        $pass = md5(md5($password));
        $pdo = $this->dataModule->getConnection();
        $sql = "SELECT * from `dzundza_account` where login = :login and password = :password";
        $stn = $pdo->prepare($sql);
        $stn->bindParam(':login', $login, PDO::PARAM_STR);
        $stn->bindParam(':password', $pass, PDO::PARAM_STR);
        $stn->execute();
        $result = $stn->fetchAll(PDO::FETCH_ASSOC);
        if (count($result) > 0) {
            return 1;
        } else {
            return 0;
        }
    }

    public function registerUser($login, $password, $email)
    {
        try {

            $pass = md5(md5($password));
            $pdo = $this->dataModule->getConnection();
            $pdo->beginTransaction();
            $sql = "INSERT into `dzundza_account`(`login`,`password`,`email`) values (:login, :password,:email)";
            $stn = $pdo->prepare($sql);
            $stn->bindParam(':login', $login, PDO::PARAM_STR);
            $stn->bindParam(':password', $pass, PDO::PARAM_STR);
            $stn->bindParam(':email', $email, PDO::PARAM_STR);
            $result = $stn->execute();
            $pdo->commit();
            $this->setUserRole($this->getRoleIdByName('guest'), $this->getUserIdByLogin($login));
            //var_dump($stn->errorInfo());
        } catch (PDOException $e) {
            $pdo->rollBack();
            echo "<pre>Error - ".$e->errorInfo."</pre><br/>";

            die();
        }
    }

    public function isAuthorizedUserVer2()
    {
        $status = -1;

        foreach ($_COOKIE as $key => $value) {
            $login = $key;
            $ipFromDB = '';
            $userIP = '';
            $hashFromCookie = $value;
            $hashFromDB = $this->getHash($this->getUserIdByLogin($login));
            if ($this->ipAssign($this->getUserIdByLogin($login))) {
                $ipFromDB = $this->getIp($this->getUserIdByLogin($login));
                $userIP = $_SERVER['REMOTE_ADDR'];
            }
            // echo "hashFromCookie = $hashFromCookie<br/>";
            // echo "hashFromDB = $hashFromDB<br/>";
            // echo "ipFromDB = $ipFromDB<br/>";
            // echo "userIP = $userIP<br/>";
            if ($hashFromCookie == $hashFromDB && $ipFromDB == $userIP) {
                $status = $key;
                break;
            } else {
                $status = -1;
                continue;
            }
        }
        return $status;
    }


    public function authorizeUserVer2($login, $password, $ip = null)
    {
        $pass = md5(md5($password));
        $pdo = $this->dataModule->getConnection();
        $sql = "SELECT * from `dzundza_account` where login = :login and password = :password";
        $stn = $pdo->prepare($sql);
        $stn->bindParam(':login', $login, PDO::PARAM_STR);
        $stn->bindParam(':password', $pass, PDO::PARAM_STR);
        $stn->execute();
        $result = $stn->fetchAll(PDO::FETCH_ASSOC);
        if (count($result) > 0) {
            $hash = $this->generateHash($login, $password);
            setcookie($login, $hash, time() + 3600, "/", $_SERVER['SERVER_NAME'], false);
            setcookie('id', $this->getUserIdByLogin($login), time() + 3600, "/", $_SERVER['SERVER_NAME'], false);
            $this->insertHashToDB($this->getUserIdByLogin($login), $hash);
            if ($ip != null) {
                $this->insertIPToDB($this->getUserIdByLogin($login), $ip);
            }
            return 1;

        } else {
            return 0;
        }
    }

    private function generateHash($login, $password)
    {
        $string = "HELLO GYUS ! I AM MAC !";
        $time = time() . "";
        $hash = md5(md5($password . crypt($string, $time) . $time) . $login);
        return $hash;
    }

    public function logout()
    {
        foreach ($_COOKIE as $key => $value) {
            if ($this->isUser($key) && $this->isAuthorizedUserVer2($key)) {
                setcookie($key, '', -1, '/');
                $this->insertHashToDB($this->getUserIdByLogin($key), '');
                $this->insertIPToDB($this->getUserIdByLogin($key), '', false);
            }
        }
    }

    public function isUser($login)
    {
        $pdo = $this->dataModule->getConnection();
        $sql = "SELECT * from `dzundza_account` where login = :login";
        $stn = $pdo->prepare($sql);
        $stn->bindParam(':login', $login, PDO::PARAM_STR);
        $stn->execute();
        $result = $stn->fetchAll(PDO::FETCH_ASSOC);
        if (count($result) > 0) {
            return 1;
        } else {
            return 0;
        }
    }

    public function getUserRoles($login = 'guest')
    {

        //echo "getUserRoles($login)<br/>";

        if ($login == 'guest' || $login['auth'] == false) return 'guest';
        if(is_array($login))
         $name = $login["name"];
        else
            $name = $login;
        //echo "user name is $name </br>";
        $pdo = $this->dataModule->getConnection();
        $idaccount = $this->getUserIdByLogin($name);

        $sql = "select roleName
                  from `dzundza_role` as er, `dzundza_account` as ea, `dzundza_account_has_role` as eahr
                   where ea.`idaccount` = :idaccount
                   and ea.`idaccount` = eahr.`account_idaccount`
                    and eahr.`role_idrole` = er.`idrole`";
        $stn = $pdo->prepare($sql);
        $stn->bindParam(':idaccount', $idaccount, PDO::PARAM_INT);
        $stn->execute();
        $result = $stn->fetch(PDO::FETCH_ASSOC);

        $role = $result['roleName'];
        if ($role == null) return 'guest';
        return $role;


    }

    public function userChangePassword($login)
    {
        $id = $this->getUserIdByLogin($login);
        $pass = crypt("dasdas" . time(), "1243q");
        $encpass = md5(md5($pass));
        $pdo = $this->dataModule->getConnection();
        $sql = "UPDATE `dzundza_account` SET `password`=:encpass  WHERE `idaccount`=:id";
        $stn = $pdo->prepare($sql);
        $stn->bindParam(':id', $id, PDO::PARAM_STR);
        $stn->bindParam(':encpass', $encpass, PDO::PARAM_STR);
        $stn->execute();
        return $pass;


    }

    private function ipAssign($id)
    {
        $pdo = $this->dataModule->getConnection();
        $sql = "SELECT `ipAssign` FROM `dzundza_account`  WHERE `idaccount`=:id";
        $stn = $pdo->prepare($sql);
        $stn->bindParam(':id', $id, PDO::PARAM_STR);
        $stn->execute();
        $result = $stn->fetch(PDO::FETCH_COLUMN);
        return $result;
    }

    private function insertIPToDB($id, $ip, $assign = true)
    {

        $pdo = $this->dataModule->getConnection();
        $sql = "UPDATE `dzundza_account` SET `ip`=:ip, `ipAssign`=:assign  WHERE `idaccount`=:id";
        $stn = $pdo->prepare($sql);
        $stn->bindParam(':ip', $ip, PDO::PARAM_STR);
        $stn->bindParam(':id', $id, PDO::PARAM_INT);
        $stn->bindParam(':assign', $assign, PDO::PARAM_BOOL);
        $result = $stn->execute();
       // if (!$result) var_dump($stn->errorInfo());

    }

    private function getIp($id)
    {
        $pdo = $this->dataModule->getConnection();
        $sql = "SELECT `ip` FROM `dzundza_account`  WHERE `idaccount`=:id";
        $stn = $pdo->prepare($sql);
        $stn->bindParam(':id', $id, PDO::PARAM_STR);
        $stn->execute();
        $result = $stn->fetch(PDO::FETCH_COLUMN);
        return $result;
    }

    private function setUserRole($roleId, $userId)
    {
        $pdo = $this->dataModule->getConnection();
        try {
            $pdo->beginTransaction();
            $sql = "INSERT INTO `dzundza_account_has_role` (`account_idaccount`, `role_idrole`)
        VALUES(:userid,:roleid)";
            $stn = $pdo->prepare($sql);
            $stn->bindParam(':userid', $userId, PDO::PARAM_INT);
            $stn->bindParam(':roleid', $roleId, PDO::PARAM_INT);
            $stn->execute();
            $pdo->commit();
        } catch (PDOException $e) {
            $pdo->rollBack();
            echo "<pre>Error - ".$e->errorInfo."</pre><br/>";

        }

    }

    private function getRoleIdByName($roleName)
    {
        $pdo = $this->dataModule->getConnection();
        $sql = "SELECT `idRole` FROM `dzundza_role` where `roleName` = :role";
        $stn = $pdo->prepare($sql);
        $stn->bindParam(':role', $roleName);
        $stn->execute();
        $result = $stn->fetch(PDO::FETCH_ASSOC);
        return $result['idRole'];
    }

    public function getIdProfile($name)
    {
        try{
            //echo "getIdProfile($name)<br/>";
        $pdo = $this->dataModule->getConnection();
        $id = $this->getUserIdByLogin($name);
        $sql = "SELECT `dzundza_userprofile`.`iduserProfile`
                FROM `dzundza_userprofile`
                WHERE `edu_account_idaccount` = :idaccount;
";
        $stn = $pdo->prepare($sql);
        $stn->bindParam(':idaccount', $id, PDO::PARAM_INT);
        $res = $stn->execute();

            if(!$res) return -1;
        $result = $stn->fetch(PDO::FETCH_COLUMN);
        $this->vardump($result);
        return $result;
            }catch(PDOException $e){
            $this->vardump($e->errorInfo);
        }
    }

}
